/**
 * 企业左侧导航
 */

import React from 'react';
import PropTypes from 'prop-types';
import { Badge } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
// import OrgAliasGuide from '../orgAliasGuide';
import utils from 'utils';
import { getCachedRepoValue } from 'utils/repoIdCache';
import { getFeature } from 'utils/features';
import { navigate, getPathWithNoRootPath } from 'utils/router';
import TagForFeature from 'components/tagForFeature';
import intl from '../../../../../../locale';

const { organization } = window.FORCE;

export default class SpaceNav extends React.Component {
  static propTypes = {
    welcomeDialogStatus: PropTypes.bool,
    // beforeShow: PropTypes.func,
    // afterClose: PropTypes.func,
    // newbieTaskStatus: PropTypes.string,
    // newbieTaskExpandStatus: PropTypes.bool,
  };

  componentDidMount() {
    const { pathname } = window.location;
    document.title = intl.get({
      id: 'code-assets.containers.home.nav.YunxiaoCodeupEnterpriseCodeManagement',
      defaultMessage: '云效 Codeup · 企业级代码管理平台',
    });
    const active = this.getActiveByPathname(pathname);
    this.initSidebar(active, true);
    if (this.props.welcomeDialogStatus === false && utils.getCachedData('group_or_repo_visited')) {
      this.showDockGuide();
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (
      nextProps.welcomeDialogStatus === false &&
      this.props.welcomeDialogStatus == null &&
      utils.getCachedData('group_or_repo_visited')
    ) {
      this.showDockGuide();
    }
    if (nextProps.pathname !== this.props.pathname) {
      this.initSidebar(this.getActiveByPathname[nextProps.pathname]);
    }
  }

  componentWillUnmount() {
    // window.TB_NAVIGATION.removeSidebar();
  }

  /**
   * 通过路径获取高亮哪个侧导项
   */
  getActiveByPathname = (pathname) => {
    const activeMap = {
      '': 'projects',
      '/': 'projects',
      '/groups': 'groups',
      '/merge_requests': 'merge_requests',
      '/trashes': 'trashes',
    };

    return activeMap[getPathWithNoRootPath(pathname)];
  };

  /**
   * 初始化侧导
   */
  initSidebar = (active, didMount) => {
    const hasSettingsAuth =
      organization.user_role === 'ADMIN' ||
      organization.user_role === 'ORG_ADMIN' ||
      organization.user_role === 'ORG_OWNER';
    const key = getCachedRepoValue('user');
    const hasCache = utils.getCachedData(`settings-repository-permissions-${key}`);
    const hasDot = !hasCache;

    let main = [
      {
        id: 'projects',
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="code-basement-line" />,
        },
        name: intl.get({
          id: 'code-assets.containers.home.nav.CodeBase',
          defaultMessage: '代码库',
        }),
        onClick: this.handleClick,
        isShow: getFeature('page_enable.org.projects'),
      },
      {
        id: 'groups',
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="folder-line" />,
        },
        name: intl.get({
          id: 'code-assets.containers.home.nav.CodeGroup',
          defaultMessage: '代码组',
        }),
        onClick: this.handleClick,
        isShow: getFeature('page_enable.org.groups'),
      },
      {
        id: 'merge_requests',
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="pull-request-line" />,
        },
        name: intl.get({
          id: 'code-assets.containers.home.nav.MergeRequest',
          defaultMessage: '合并请求',
        }),
        onClick: this.handleClick,
        isShow: getFeature('page_enable.org.merge_requests'),
      },
    ];

    main.push({
      id: 'trashes',
      icon: {
        useJsx: true,
        jsx: <YunxiaoIcon type="delete-line" />,
      },
      name: (
        <span>
          {intl.get({
            id: 'code-assets.containers.home.nav.RecycleBin',
            defaultMessage: '回收站',
          })}
          <TagForFeature
            prefix="yx-"
            type="primary"
            size="small"
            style={{ marginLeft: 8 }}
            tagText="BETA"
          />
        </span>
      ),
      onClick: this.handleClick,
      isShow: getFeature('page_enable.org.trashes'),
    });
    main = main.filter(va => va.isShow);
    window.TB_NAVIGATION.initSidebar &&
      window.TB_NAVIGATION.initSidebar({
        active,
        main,
        extra: getFeature('page_enable.org.setting') && hasSettingsAuth
          ? [
              {
                id: 'settings',
                icon: {
                  useJsx: true,
                  jsx: <YunxiaoIcon type="setting-line" />,
                },
                name: (
                  <Badge className="nav-setting-repository-permissions" dot={hasDot}>
                    {intl.get({
                      id: 'code-assets.containers.home.nav.EnterpriseSettings',
                      defaultMessage: '企业设置',
                    })}
                  </Badge>
                ),
                onClick: this.handleClick,
              },
            ]
          : null,
      });
    if (didMount) {
      window.TB_NAVIGATION.ready(() => {
        window.TB_NAVIGATION.onSidebarChange(({ isStick }) => {
          const task = document.querySelector('.codeup-newbie-task');
          const guide = document.querySelector('.org-alias_guide');
          this.props.onSidebarChange(isStick);
          if (task) {
            if (isStick) {
              task.style.width = 'calc(100% - 220px)';
            } else {
              task.style.width = 'calc(100% - 64px)';
            }
          }
          if (guide) {
            if (isStick) {
              guide.style.left = '247px';
            } else {
              guide.style.left = '92px';
            }
          }
        });
      });
    }
  };

  handleClick = (v) => {
    document.title = intl.get({
      id: 'code-assets.containers.home.nav.YunxiaoCodeupEnterpriseCodeManagement',
      defaultMessage: '云效 Codeup · 企业级代码管理平台',
    });
    if (v.id === '/settings/repository_permissions') {
      const key = getCachedRepoValue('user');
      const hasCache = utils.getCachedData(`settings-repository-permissions-${key}`);
      if (!hasCache) {
        utils.setCachedData(`settings-repository-permissions-${key}`, true);
      }
    }

    const defaultPathMap = {
      projects: '/?navKey=mine',
      groups: '/groups?navKey=mine',
      merge_requests: '/merge_requests?navKey=all&search=created',
      trashes: '/trashes',
      settings: '/settings/repository_permissions',
    };

    navigate(defaultPathMap[v.id]);
  };

  showDockGuide = () => {
    window.TB_NAVIGATION.Dock.showDockGuide &&
      window.TB_NAVIGATION.Dock.showDockGuide({
        onOk: () => {},
      });
  };

  render() {
    return null;

    // 指向企业设置的引导框，需要时再打开
    // const {
    //   beforeShow,
    //   afterClose,
    //   newbieTaskStatus,
    //   welcomeDialogStatus,
    //   newbieTaskExpandStatus,
    // } = this.props;
    // const isSidebarStick = window.localStorage.isSidebarStick === 'true';

    // return (
    //   <Location>
    //     {() => {
    //       return (
    //         <React.Fragment>
    //           <OrgAliasGuide
    //             style={{
    //               position: 'fixed',
    //               left: isSidebarStick ? '247px' : '92px',
    //               bottom: '10px',
    //               width: '230px',
    //               zIndex: 100,
    //             }}
    //             beforeShow={beforeShow}
    //             afterClose={afterClose}
    //             newbieTaskStatus={newbieTaskStatus}
    //             welcomeDialogStatus={welcomeDialogStatus}
    //             newbieTaskExpandStatus={newbieTaskExpandStatus}
    //           />
    //         </React.Fragment>
    //       );
    //     }}
    //   </Location>
    // );
  }
}
